package br.com.queroprestador.endpoint;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

import br.com.queroprestador.interfaces.EndPoint;
import br.com.queroprestador.model.User;
import br.com.queroprestador.sevices.AutenticadorApi;

public class SignInEndPoint implements EndPoint{

	@Override
	public void getEndPoint(HttpServletRequest req, HttpServletResponse res) throws Exception {
		
		RequestDispatcher rd = req.getRequestDispatcher("/user/index.jsp");
		
		
		String user = req.getParameter("user");
		String password = req.getParameter("password");
		
		AutenticadorApi auth = new AutenticadorApi();
		String json = auth.signIn(user, password);
		
		User usr = getUser(json);
		
		try {
			rd.forward(req, res);
		} catch (ServletException e) {
			
			e.printStackTrace();
		}
		
		
	}
	
	private User getUser(String json) throws JSONException{
		
		User user = new User();
		
		JSONObject jsonObject = new JSONObject(json);
		user.setName(jsonObject.getString("name"));
		user.setCpf(jsonObject.getString("cpf"));
		user.setEmail(jsonObject.getString("email"));
		user.setPassword(jsonObject.getString("password"));
		user.setId(jsonObject.getLong("id"));
		
		return user;
	}
	

}
